﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using Oxage.Common;
using Oxage.Drivers;
using Oxage.Models;
using Oxage.Services;

namespace Oxage
{
	public partial class App : Application
	{
		public App()
		{
			//Set logging output
			Logger.Handlers = new List<ILogger>()
			{
				new ConsoleLogger(),
				//new FileLogger() { Path = "log.txt" }
			};

			//Attach global exception handlers
			AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
			{
				Logger.Log(e.ExceptionObject as Exception);
			};
			this.DispatcherUnhandledException += (sender, e) =>
			{
				Logger.Log(e.Exception);
				e.Handled = true;
			};

			//Initialize main model
			ViewModel = new MainViewModel();

			//Initialize services
			BuildService.CurrentProjectBuilder = new GCodeProjectBuilder();
			DebugService.CurrentProjectDebugger = new GCodeProjectDebugger();
			DebugService.CurrentMachineController = new NetduinoDriver();

			//TODO: Improve quick work-around, update with newer version when available
			try
			{
				//Create missing machine configuration file
				if (!File.Exists("machine.ini"))
				{
					string content = ResourceHelper.GetString("Resources/Samples/machine.ini");
					File.WriteAllText("machine.ini", content);
				}

				//Create missing program configuration file
				if (!File.Exists("program.ini"))
				{
					string content = ResourceHelper.GetString("Resources/Samples/program.ini");
					File.WriteAllText("program.ini", content);
				}
			}
			catch
			{
			}
		}

		/// <summary>
		/// Gets or sets a globally accessible MainViewModel instance.
		/// </summary>
		public static MainViewModel ViewModel
		{
			get;
			set;
		}
	}
}
